package com.harmonyos.cases.action;

import com.harmonyos.cases.bean.CodeInfo;
import com.harmonyos.cases.constants.Constants;
import com.harmonyos.cases.listener.CodeListener;
import com.harmonyos.cases.listener.GitListener;
import com.harmonyos.cases.view.PluginDialog;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.Objects;

import static com.harmonyos.cases.utils.InsertUtils.*;

public class DemoTestAction extends AnAction {

    @Override
    public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
        // 打开自定义对话框
        PluginDialog dialog = new PluginDialog();
        dialog.setCodeListener(new CodeListenerImpl(anActionEvent));
        dialog.show();
    }

    public static class CodeListenerImpl implements CodeListener {
        private final AnActionEvent anActionEvent;

        public CodeListenerImpl(AnActionEvent anActionEvent) {
            this.anActionEvent = anActionEvent;
        }

        @Override
        public AnActionEvent getActionEvent() {
            return anActionEvent;
        }

        @Override
        public void insertCode(String type, CodeInfo codeInfo, String downloadPath) {
            if (type.equals(Constants.PLUGIN_CATEGORY_CASE)) {
                if (downloadPath != null && !downloadPath.isEmpty()) {
                    String[] temp = codeInfo.getCasePath().split("/");
                    File downloadDir = new File(downloadPath + "\\" + temp[temp.length - 1]);
                    if (!downloadDir.exists()) {
                        downloadDir.mkdirs();
                    }
                    downloadPath = downloadDir.getAbsolutePath();
                    downloadCode(Objects.requireNonNull(this.anActionEvent.getProject()), downloadPath, codeInfo.getCasePath(), codeInfo.getCaseRepositoriesInfo(), new GitListener() {
                        @Override
                        public void onGitResult(String result) {
                            Notification notification = new Notification(Constants.PLUGIN_TITLE, Constants.PLUGIN_NOTIFICATION_TIP, result, NotificationType.INFORMATION);
                            Notifications.Bus.notify(notification, anActionEvent.getProject());
                        }
                    });
                }
            }
            if (type.equals(Constants.PLUGIN_CATEGORY_LIBRARY)) {
                insertCodeAtCaret(this.anActionEvent, codeInfo.getInsertCode());
                insertImportCode(this.anActionEvent, codeInfo.getImportCode());
                writeDependenciesCode(this.anActionEvent, codeInfo.getDependenciesName(), codeInfo.getDependenciesVersion());
            }
        }
    }

}
